<?php

namespace App\Admin\Actions\Grid\Row\SwtOrder;

use App\Http\Logic\OrderLogic;
use App\Models\SwtOrder;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class NotifyOrder extends RowAction
{
    /**
     * @return string
     */
    protected $title = '回调';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $out_order_no = $request->get('order_sn');

        $order_id = $request->get('order_id');

        $pay_amount = $request->get('pay_amount');

        $user_id = $request->get('user_id');

        $payment_at = date('Y-m-d H:i:s', time());

        $res = OrderLogic::notifyOrder($order_id, $out_order_no, $pay_amount, $user_id, $payment_at);

        if(!$res) {
            return $this->response()
                ->error('大黄鹅订单回调失败')
                ->refresh();
        }

        return $this->response()
            ->success('回调成功')
            ->refresh();
    }

    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return ['确认操作吗?', '回将当前订单状态同步至大黄鹅后台'];
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [
            'order_id'   => $this->row->id,
            'order_sn'   => $this->row->order_sn,
            'pay_amount' => $this->row->pay_amount,
            'user_id'    => $this->row->user_id
        ];
    }

    protected function html()
    {
        return <<<HTML
            <a {$this->formatHtmlAttributes()}><i class="feather icon-cloud text-info"></i> <span class="text-info">{$this->title}</span> &emsp;</a>
        HTML;
    }
}
